//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import LocalNodeWrap from '../LocalNodeWrap';
import type { NodeData } from '../types';
import { Button, Descriptions } from 'antd';
import type { CdnDomainInfo } from "@/api/tencloud/cdn";
import { listDomain, queryData } from "@/api/tencloud/cdn";
import { get_source, type TenCloudSourceInfo, type UserDataSourceInfo } from '@/api/user_dataview';
import moment from 'moment';
import { ReloadOutlined } from '@ant-design/icons';

const TenCloudCdnStatusNode = (props: NodeProps<NodeData>) => {

    const [domainInfo, setDomainInfo] = useState<CdnDomainInfo | null>(null);
    const [dayReqCount, setDayReqCount] = useState(0);
    const [dayDownSize, setDayDownSize] = useState(0);
    const [weekReqCount, setWeekReqCount] = useState(0);
    const [weekDownSize, setWeekDownSize] = useState(0);
    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const getSizeStr = (size: number) => {
        let tmpSize = size;
        if (tmpSize < 1024) {
            return `${tmpSize}B`;
        }
        tmpSize /= 1024;
        if (tmpSize < 1024) {
            return `${tmpSize.toFixed(1)}K`;
        }
        tmpSize /= 1024;
        if (tmpSize < 1024) {
            return `${tmpSize.toFixed(1)}M`;
        }
        tmpSize /= 1024;
        if (tmpSize < 1024) {
            return `${tmpSize.toFixed(1)}G`;
        }
        tmpSize /= 1024;
        return `${tmpSize.toFixed(1)}T`;

    }

    const loadDomainInfo = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as TenCloudSourceInfo;
        const domain = props.data.extraInfo as string;
        const res = await listDomain(sourceInfo.secretId, sourceInfo.secretKey, [domain]);
        if (res.Response.Domains.length == 1) {
            setDomainInfo(res.Response.Domains[0]);
        }
    };

    const loadDayStatus = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as TenCloudSourceInfo;
        const domain = props.data.extraInfo as string;
        const startDay = moment();
        const endDay = moment().add(1, "days");

        const fluxRes = await queryData(sourceInfo.secretId, sourceInfo.secretKey, domain, "flux", startDay, endDay);
        setDayDownSize(fluxRes.Response.Data[0].CdnData[0].SummarizedData.Value);
        const requestRes = await queryData(sourceInfo.secretId, sourceInfo.secretKey, domain, "request", startDay, endDay);
        setDayReqCount(requestRes.Response.Data[0].CdnData[0].SummarizedData.Value);
    };

    const loadWeekStatus = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as TenCloudSourceInfo;
        const domain = props.data.extraInfo as string;
        const startDay = moment().add(-6, "days");
        const endDay = moment().add(1, "days");

        const fluxRes = await queryData(sourceInfo.secretId, sourceInfo.secretKey, domain, "flux", startDay, endDay);
        setWeekDownSize(fluxRes.Response.Data[0].CdnData[0].SummarizedData.Value);
        const requestRes = await queryData(sourceInfo.secretId, sourceInfo.secretKey, domain, "request", startDay, endDay);
        setWeekReqCount(requestRes.Response.Data[0].CdnData[0].SummarizedData.Value);
    };

    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(()=>{
        if(dataSource != undefined){
            loadDomainInfo();
            loadDayStatus();
            loadWeekStatus();
        }
    },[dataSource]);

    return (
        <LocalNodeWrap title={`加速域名:${props.data.extraInfo}`} nodeData={props} canChangeBgColor
            extraButtonList={[
                <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    loadDayStatus();
                    loadWeekStatus();
                }} title='刷新' />
            ]}>
            <Descriptions column={1} bordered style={{ backgroundColor: props.data.bgColor ?? "white", overflowY: "scroll", height: props.data.height - 90 }}
                labelStyle={{ backgroundColor: props.data.bgColor ?? "white", width: "100px" }}>
                {domainInfo != null && (
                    <Descriptions.Item label="上游站点">{domainInfo.Origin.Origins.join(",")}</Descriptions.Item>
                )}
                <Descriptions.Item label="当天请求数">{dayReqCount}</Descriptions.Item>
                <Descriptions.Item label="当天流量">{getSizeStr(dayDownSize)}</Descriptions.Item>
                <Descriptions.Item label="一周请求数">{weekReqCount}</Descriptions.Item>
                <Descriptions.Item label="一周流量">{getSizeStr(weekDownSize)}</Descriptions.Item>
            </Descriptions>
        </LocalNodeWrap>
    );
}

export default TenCloudCdnStatusNode;